package org.sang.bbbig.controller;

import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.sang.bbbig.model.Local;
import org.sang.bbbig.model.Student;
import org.sang.bbbig.model.Temperature;
import org.sang.bbbig.model.User;
import org.sang.bbbig.service.StuService;
import org.sang.bbbig.util.GeneralResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class StuController {
    @Autowired
    StuService stuService;

    @Autowired
    private InfluxDB influxDB;

    @Value("${spring.influx.database}")
    private String database;

//
    @PostMapping("/login")
    public GeneralResponse login(@RequestParam String name, @RequestParam String pwd,HttpServletRequest request){
        GeneralResponse g=new GeneralResponse();
        List<User> users=stuService.login1();

        for (User u:users){
            if(pwd.equals(u.getPassword()) && name.equals(u.getName())){
                request.getSession().setAttribute("user",name);
                g.setSuccess(true);
                return g; } }
        g.setMessage("账号密码错误");
        return g;
    }
    @PostMapping("/login1")
    public GeneralResponse loginin(HttpServletRequest request){
        GeneralResponse g=new GeneralResponse();
        Object success=request.getSession().getAttribute("user");
        if (success==null){
            g.setSuccess(false);
            g.setMessage("error");
            return g;
        }else if(success.equals("坤坤")){
            g.setSuccess(true);
            g.setMessage("欢迎登录,管理员");
        }else {
            g.setSuccess(true);
            g.setMessage("欢迎登录"+success);
        }
        return g;
    }


    @GetMapping("/getbyid")
    public GeneralResponse getbyid(@RequestParam int id){
        List<Student> s=new ArrayList<>();
        GeneralResponse g=new GeneralResponse();
         g.setSuccess(true);
         s.add(stuService.getById(id));
         g.setData(s);
         return g;
    }

    @GetMapping("/students")
    public GeneralResponse student(){
        GeneralResponse g=new GeneralResponse();

        g.setSuccess(true);
        g.setData(stuService.getall());
        System.out.println(g.toString());
        return g;
    }

    @PostMapping("/stu/add")
    public GeneralResponse addstud(@RequestParam int id,@RequestParam String  name,@RequestParam String password,@RequestParam String classroom,@RequestParam String gender){
        Student s=new Student();
        s.setId(id);
        s.setName(name);
        s.setPassword(password);
        s.setClassroom(classroom);
        s.setGender(gender);
        GeneralResponse g=new GeneralResponse();
        g.setSuccess(true);
        g.setData(stuService.addstud(s));
        return g;
    }

    @PutMapping("/update")
    public GeneralResponse updateStud(@RequestParam int id,@RequestParam String  name,@RequestParam String password,@RequestParam String classroom,@RequestParam String gender){
        Student s=new Student();
        s.setId(id);
        s.setName(name);
        s.setPassword(password);
        s.setClassroom(classroom);
        s.setGender(gender);

        GeneralResponse g=new GeneralResponse();
        g.setSuccess(true);
        g.setData(stuService.updatestud(s));
        return g;
    }

    @PostMapping("delete")
    public GeneralResponse delete(@RequestParam int id){
        GeneralResponse g=new GeneralResponse();
        g.setSuccess(true);
        g.setData(stuService.deletstud(id));
        return g;
    }
//    @RequestParam float lng,@RequestParam float lat
    @GetMapping("/location")
    public void location(@RequestParam float lng,@RequestParam float lat){
        Date date=new Date();
        influxDB.write(Point.measurement("route1")
                .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
                .tag("machine", "gaode")
                .tag("type", "map")
                .addField("long", lng)
                .addField("lat", lat)
                .build());
    }

    @GetMapping("/e")
    public void test2(){
        System.out.println("---开始查询数据---");
        String querycondetion="";

        String queryCmd=" select  latitude,longitude from "+"temperature1 "+querycondetion;

        QueryResult queryResult = influxDB.query(new Query(queryCmd, database));
        System.out.println("原始数据为： "+queryResult);

        List<QueryResult.Result> results=queryResult.getResults();
        if(results==null)
            return ;
        QueryResult.Result result=results.get(0);
        List<QueryResult.Series> seriesList=result.getSeries();

        for (QueryResult.Series series:seriesList ){
            if(series==null)
                return;
            System.out.println("结果数量为：" + (series.getValues() == null ?
                    0 : series.getValues().size()));
            System.out.println("colums ==>>"+series.getColumns());
            System.out.println("Tag ==>>"+series.getTags());
            System.out.println("name ==>>"+series.getName());
            System.out.println("values ==>>"+series.getValues());
            List<List<Object>> sc=series.getValues();
            Object[] obj= sc.toArray();
            System.out.println(obj[1]);
            Object aa=obj[1];

        }
    }

    @GetMapping("/t")
    public GeneralResponse test3() {
        System.out.println("---开始查询数据---");
        String queryCondition = "";  //查询条件暂且为空
        // 此处查询所有内容,如果
        String queryCmd = "SELECT lat,long FROM "
                // 要指定从 RetentionPolicyName.measurement中查询指定数据,默认的策略可以不加；
                // + 策略name + "." + measurement
                + "location"
                // 添加查询条件(注意查询条件选择tag值,选择field数值会严重拖慢查询速度)
                + queryCondition
                // 查询结果需要按照时间排序
                + " ORDER BY time ";
        // 开始查询
        QueryResult queryResult = influxDB.query(new Query(queryCmd, database),
                TimeUnit.MILLISECONDS);
        System.out.println("原始结果为：" + queryResult);

        // 获取查询结果
        List<QueryResult.Result> results = queryResult.getResults();
        if (results == null) {
            return null;
        }
        // 多个sql用分号隔开，因本次查询只有一个sql，所以取第一个就行
        List<Local> locals=new ArrayList<>();
        QueryResult.Result result = results.get(0);
        List<QueryResult.Series> seriesList = result.getSeries();
        List<Temperature> temperatureList = new LinkedList<>();

        GeneralResponse g=new GeneralResponse();
        for (QueryResult.Series series : seriesList) {
            if (series == null) {
                return null;
            }
            series.getValues().forEach(valueData -> {
                Temperature temperature = new Temperature();
                Local l=new Local();
                temperature.setExternal(Float.valueOf(valueData.get(1).toString()));
                temperature.setInternal(Float.valueOf(valueData.get(2).toString()));
                System.out.println("lat:"+temperature.getExternal()+"   long:"+temperature.getInternal());
                temperatureList.add(temperature);
                l.setLat(temperature.getExternal());
                l.setLng(temperature.getInternal());
                locals.add(l);
            });
        }
        g.setSuccess(true);
        g.setData(locals);
        System.out.println(g.toString());
        return g;
    }
//    @RequestParam String table
    @GetMapping("/route")
    public GeneralResponse route() {
        System.out.println("---开始查询数据---");
        String queryCondition = " where time >= 1653204366356000000 and time<=1653205542098000000";  //查询条件暂且为空
        // 此处查询所有内容,如果
        String queryCmd = "SELECT lat,long FROM route1" + queryCondition;
        // 开始查询
        QueryResult queryResult = influxDB.query(new Query(queryCmd, database),
                TimeUnit.MILLISECONDS);
        System.out.println("原始结果为：" + queryResult);

        // 获取查询结果
        List<QueryResult.Result> results = queryResult.getResults();
        if (results == null) {
            return null;
        }
        // 多个sql用分号隔开，因本次查询只有一个sql，所以取第一个就行
        List<Local> locals=new ArrayList<>();
        QueryResult.Result result = results.get(0);
        List<QueryResult.Series> seriesList = result.getSeries();
        List<Temperature> temperatureList = new LinkedList<>();

        GeneralResponse g=new GeneralResponse();
        for (QueryResult.Series series : seriesList) {
            if (series == null) {
                return null;
            }
            series.getValues().forEach(valueData -> {
                Temperature temperature = new Temperature();
                Local l=new Local();
                temperature.setExternal(Float.valueOf(valueData.get(1).toString()));
                temperature.setInternal(Float.valueOf(valueData.get(2).toString()));
                System.out.println("lat:"+temperature.getExternal()+"   long:"+temperature.getInternal());
                temperatureList.add(temperature);
                l.setLat(temperature.getExternal());
                l.setLng(temperature.getInternal());
                locals.add(l);
            });
        }
        g.setSuccess(true);
        g.setData(locals);
        System.out.println(g.toString());
        return g;
    }

}
